<template>
  <div class="app-container">
    <div class="main">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleFormRef" label-width="86px">
        <el-form-item label="消息类型" prop="type">
          <el-radio-group v-model="ruleForm.type">
            <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.id">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 第一期不弄 -->
        <!-- <el-form-item label="品牌" prop="type">
        </el-form-item> -->

        <template v-if="[1, 2, 3, 4].includes(ruleForm.type)">
          <el-form-item label="推送方式" prop="pushType">
            <el-radio-group v-model="ruleForm.pushType">
              <el-radio v-for="(item, index) in PushTypeOptions" :key="index" :label="item.id">
                {{ item.id === 2 ? ruleForm.type === 4 ? item.label[1]
                  : item.label[0] : item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="ruleForm.pushType === 2">
            <div class="appoint_warp">
              <!-- 指定单个设备 -->
              <template v-if="ruleForm.type === 4">
                <el-button type="warning" plain icon="el-icon-plus" @click="handleSelectDevice">选择设备</el-button>
                <div class="selected_warp" v-show="selectDeviceCode">已选设备 {{ selectDeviceCode }}</div>
              </template>
              <!-- 指定多个用户 -->
              <template v-else>
                <el-button type="warning" plain icon="el-icon-plus" @click="handleSelectUsers">选择用户</el-button>
                <div class="selected_warp" v-show="selectUserNum > 0">已选 {{ selectUserNum }}</div>
              </template>
            </div>
          </el-form-item>
        </template>

        <!-- 升级信息的时候需要填写版本 -->
        <template v-if="ruleForm.type === 3">
          <el-form-item label="当前版本" prop="currentVersion">
            <el-radio-group v-model="ruleForm.currentVersion">
              <el-radio v-for="(item, index) in upgradeOptions" :key="index" :label="item.targetVersion">
                {{ item.targetVersion }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="目标版本" prop="targetVersion">
            <el-radio-group v-model="ruleForm.targetVersion">
              <el-radio v-for="(item, index) in upgradeOptions" :key="index" :label="item.targetVersion">
                {{ item.targetVersion }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <!-- 升级信息的时候需要填写版本 -->
        <template v-if="ruleForm.type === '5,6'">
          <!-- 后端这个位置没弄，跟他说过 -->
          <el-form-item label="协议类型" prop="protocolType">
            <el-radio-group v-model="ruleForm.protocolType">
              <el-radio v-for="(item, index) in protocolTypeOptions" :key="index" :label="item.id">
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="协议地址" prop="message" class="msg_con_warp">
            <el-input v-model="ruleForm.message" placeholder="请输入推送内容，按Enter键进行换行"></el-input>
          </el-form-item>
        </template>

        <template v-if="[1, 2, 3].includes(ruleForm.type)">
          <el-form-item label="消息标题" prop="title">
            <el-input v-model="ruleForm.title" show-word-limit :maxlength="255"></el-input>
          </el-form-item>
          <el-form-item label="推送内容" prop="message" class="msg_con_warp">
            <el-input v-model="ruleForm.message" type="textarea" show-word-limit :maxlength="500"
              placeholder="请输入推送内容，按Enter键进行换行"></el-input>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="warning" @click="handleFromSubmit('ruleFormRef')">立即推送</el-button>
          <el-button type="info" plain @click="handleFromCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <AddSelectUsersDrawer :visible.sync="drawerAddSelectUserVisible" :info-data="selectUserInfoData"
      :brand-options="brandOptions" @addSelectSuccessChange="addSelectSuccessChange" />

    <AddSelectDeviceDrawer :visible.sync="drawerAddSelectDeviceVisible" :info-data="selectDeviceInfoData"
      :brand-options="brandOptions" @addSelectSuccessChange="addSelectSuccessChange" />
  </div>
</template>
<script>
import { getMenufacturers } from "@/api/family-and-users-management/index"
import AddSelectUsersDrawer from './components/AddSelectUsersDrawer.vue'
import AddSelectDeviceDrawer from './components/AddSelectDeviceDrawer.vue'
import { addMessage } from "@/api/message-management/family/list"
import { fetchList as upgradeFetchList } from "@/api/ota-upgrade-management/list"

export default {
  components: {
    AddSelectUsersDrawer,
    AddSelectDeviceDrawer,
  },
  data() {
    let com_blur__rule = [{ required: true, message: '此字段为必填。', trigger: 'blur' }],
      com_change__rule = [{ required: true, message: '此字段为必填。', trigger: 'change' }];
    return {
      ruleForm: {
        type: 1,// 消息类型，1系统消息，2家庭圈消息，3升级，4，日志上传 5，隐私协议变更消息
        pushType: 1,
        receiverName: [],//这个是接收者，要么全部，要么选定用户，要么选定设备 

        // 版本号
        targetVersion: '',
        currentVersion: '',

        // 协议
        protocolType: 5,

        title: '',
        message: '',
      },
      brandOptions: [],
      upgradeOptions: [],
      // 信息类型数组
      typeOptions: [
        { id: 1, label: '系统消息' },
        { id: 3, label: '升级消息' },
        { id: 4, label: '日志消息' },
        { id: '5,6', label: '隐私协议变更消息' },
      ],
      // 推送方式数组
      pushTypeOptions: [
        { id: 1, label: '全部用户' },
        { id: 2, label: ['指定用户', '指定设备用户'] },
      ],
      PushTypeOptions: [],// 各种状态下推送方式的数组
      // 协议类型数组
      protocolTypeOptions: [
        { id: 5, label: '用户协议' },
        { id: 6, label: '隐私政策' },
      ],

      rules: {
        type: com_change__rule,
        pushType: com_change__rule,

        targetVersion: com_change__rule,
        currentVersion: com_change__rule,

        protocolType: com_change__rule,

        title: com_blur__rule,
        message: com_blur__rule,
      },

      // 选择用户弹窗
      selectUserInfoData: null,
      drawerAddSelectUserVisible: false,
      // 选择设备弹窗
      selectDeviceInfoData: null,
      drawerAddSelectDeviceVisible: false,
    }
  },
  computed: {
    selectDeviceCode() {
      let a = this.ruleForm.receiverName;
      try {
        return a[0].deviceCode || ''
      } catch (error) { }
      return ''
    },
    selectUserNum() {
      let a = this.ruleForm.receiverName;
      try {
        return a.length
      } catch (error) { }
      return 0
    },
  },
  watch: {
    'ruleForm.type': {
      immediate: true,
      handler(newVal) {
        this.ruleForm.receiverName = []
        let pto_arr = JSON.parse(JSON.stringify(this.pushTypeOptions));
        if (newVal === 4) {
          this.ruleForm.pushType = 2
          this.PushTypeOptions = [pto_arr[1]]

        } else {
          this.PushTypeOptions = pto_arr
        }
      }
    }
  },
  created() {
    // 获取品牌
    getMenufacturers({ pageNum: 1, pageSize: 1000 }).then(res => {
      if (res.code === 200) {
        this.brandOptions = res.data.list || []
      }
    })
    // 获取所有升级信息
    upgradeFetchList({ pageNum: 1, pageSize: 1000 }).then(res => {
      if (res.code === 200) {
        this.upgradeOptions = res.data.list || []
      }
    })
  },
  methods: {
    addSelectSuccessChange(e) {
      // console.log(e);
      this.selectUserInfoData = null
      this.ruleForm.receiverName = e ? e : ''
    },
    handleSelectUsers() {
      let infoD = this.ruleForm.receiverName
      this.selectUserInfoData = infoD || []
      this.drawerAddSelectUserVisible = true
    },
    handleSelectDevice() {
      let infoD = this.ruleForm.receiverName
      this.selectDeviceInfoData = infoD || []
      this.drawerAddSelectDeviceVisible = true
    },
    handleFromSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let type = this.ruleForm.type
          if (this.ruleForm.pushType === 2) {
            if (type === 4) {
              if (!this.selectDeviceCode) {
                this.$message.error(`推送指定设备时，设备不能为空`)
                return
              }
            }
            if (this.selectUserNum === 0) {
              this.$message.error(`推送指定用户时，用户不能为空`)
              return
            }
          }

          let params = { ...this.ruleForm }
          let recName = params.receiverName;

          if (recName) {
            let rv = type === 4 ? 'deviceCode' : 'username'
            params.receiverName = recName.map(el => el[rv])
          } else {
            delete params.receiverName
          }
          if (this.ruleForm.type === 3) {
            params.describe = JSON.stringify({
              targetVersion: params.targetVersion,
              currentVersion: params.currentVersion,
            })
          }
          if (this.ruleForm.type === '5,6') {
            params.type = this.ruleForm.protocolType
          }
          delete params.protocolType

          addMessage(params).then(res => {
            console.log(res);
            if (res.code === 200) {
              this.$message.success(`添加信息成功!`)
              this.$router.push('/message/family/list')
              return
            } else {
              this.$message.error(`添加信息失败。`)
            }
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleFromCancel() {
      this.$router.push('/message/family/list')
    },
  }
}
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;
  overflow: auto;
  display: flex;

  &>.main {
    flex: 1;
    background-color: #fff;
    border-radius: 16px;
    padding: 20px;
  }
}

@mixin item_bgc_template {
  border-radius: 4px;
  background: #F5F5F5;
}

.appoint_warp {
  @include item_bgc_template;
  padding: 12px 20px;
  display: flex;
  align-items: center;

  .selected_warp {
    padding-left: 20px;
    font-size: 14px;
    color: #15181D;
  }
}

::v-deep {
  .msg_con_warp {
    .el-textarea__inner {
      min-height: 200px !important;
    }
  }
}
</style>